package top.byteio.common.core.lambda;

import lombok.extern.slf4j.Slf4j;
import top.byteio.common.core.utils.CommonUtils;

import java.lang.invoke.SerializedLambda;
import java.lang.reflect.Method;

@Slf4j
public class BeanFunctionUtils{


    /**
     * 转换方法引用为属性名
     * @param irf get函数接口
     * @return java.lang.String
     * @author lerry
     * @since 2023/7/8 15:27
     */
    public static <T> String getBeanProperty(TFunction<T> irf){
        try {
            // 提取SerializedLambda并缓存
            Method method = irf.getClass().getDeclaredMethod("writeReplace");
            method.setAccessible(Boolean.TRUE);
            SerializedLambda lambda = (SerializedLambda) method.invoke(irf);
            // 获取方法名
            String methodName = lambda.getImplMethodName();

            String prefix = null;
            if(methodName.startsWith("get")){
                prefix = "get";
            }
            else if(methodName.startsWith("is")){
                prefix = "is";
            }
            if(prefix == null){
                log.error("无效的getter方法:{}", methodName);
                prefix = "";
            }
            // 截取get/is之后的字符串并转换首字母为小写
            return CommonUtils.toLowerCaseFirstOne(methodName.replace(prefix, ""));
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


}
